package com.example.backend.controller;

import com.example.backend.domain.entity.SystemLog;
import com.example.backend.domain.entity.SystemNotification;
import com.example.backend.dto.ApiResponse;
import com.example.backend.dto.PageResult;
import com.example.backend.dto.SystemSettingDto;
import com.example.backend.dto.SaveSettingRequest;
import com.example.backend.dto.BatchSaveSettingsRequest;
import com.example.backend.dto.NotificationTestRequest;
import com.example.backend.dto.IntegrationTestRequest;
import com.example.backend.dto.TestResultDto;
import com.example.backend.constants.RoleConstants;
import com.example.backend.security.RequirePermission;
import com.example.backend.service.SystemSettingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.Map;

/**
 * 系统设置控制器
 */
@RestController
@RequestMapping("/api/settings")
@Tag(name = "系统设置", description = "系统设置和配置管理")
@SecurityRequirement(name = "Bearer Authentication")
public class SystemSettingController {
    
    private final SystemSettingService systemSettingService;
    
    public SystemSettingController(SystemSettingService systemSettingService) {
        this.systemSettingService = systemSettingService;
    }
    
    // ========== 系统设置管理 ==========
    
    @GetMapping("/{category}")
    @Operation(summary = "获取系统设置", description = "根据分类获取系统设置")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<Map<String, String>>> getSettings(
            @Parameter(description = "设置分类") @PathVariable String category) {
        try {
            Map<String, String> settings = systemSettingService.getSettingsByCategory(category);
            return ResponseEntity.ok(ApiResponse.success(settings));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取设置失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/{category}/{key}")
    @Operation(summary = "获取单个设置", description = "根据分类和键获取单个设置")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<SystemSettingDto>> getSetting(
            @Parameter(description = "设置分类") @PathVariable String category,
            @Parameter(description = "设置键") @PathVariable String key) {
        try {
            return systemSettingService.getSetting(category, key)
                    .map(setting -> ResponseEntity.ok(ApiResponse.success(setting)))
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取设置失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/{category}")
    @Operation(summary = "保存系统设置", description = "保存单个系统设置")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<SystemSettingDto>> saveSetting(
            @Parameter(description = "设置分类") @PathVariable String category,
            @Valid @RequestBody SaveSettingRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long userId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            SystemSettingDto setting = systemSettingService.saveSetting(category, request, userId);
            return ResponseEntity.ok(ApiResponse.success("设置保存成功", setting));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("保存设置失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/{category}/batch")
    @Operation(summary = "批量保存设置", description = "批量保存系统设置")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<List<SystemSettingDto>>> batchSaveSettings(
            @Parameter(description = "设置分类") @PathVariable String category,
            @Valid @RequestBody BatchSaveSettingsRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long userId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            List<SystemSettingDto> settings = systemSettingService.batchSaveSettings(category, request, userId);
            return ResponseEntity.ok(ApiResponse.success("批量保存成功", settings));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("批量保存失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/categories")
    @Operation(summary = "获取所有分类", description = "获取所有设置分类")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<List<String>>> getAllCategories() {
        try {
            List<String> categories = systemSettingService.getAllCategories();
            return ResponseEntity.ok(ApiResponse.success(categories));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取分类失败: " + e.getMessage()));
        }
    }
    
    @GetMapping
    @Operation(summary = "分页获取设置", description = "分页获取系统设置列表")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResult<SystemSettingDto>>> getSettingsList(
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword,
            Pageable pageable) {
        try {
            Page<SystemSettingDto> page = systemSettingService.getSettings(category, keyword, pageable);
            return ResponseEntity.ok(ApiResponse.success(PageResult.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取设置列表失败: " + e.getMessage()));
        }
    }
    
    // ========== 通知测试 ==========
    
    @PostMapping("/notifications/test")
    @Operation(summary = "测试通知", description = "测试通知功能")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<TestResultDto>> testNotification(
            @Valid @RequestBody NotificationTestRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long userId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            TestResultDto result = systemSettingService.testNotification(request, userId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("通知测试失败: " + e.getMessage()));
        }
    }
    
    // ========== 集成测试 ==========
    
    @PostMapping("/integrations/test")
    @Operation(summary = "测试集成", description = "测试集成功能")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<TestResultDto>> testIntegration(
            @Valid @RequestBody IntegrationTestRequest request) {
        try {
            // 这里应该从当前登录用户获取用户ID，暂时使用固定值
            Long userId = 1L; // TODO: 从JWT Token中获取当前用户ID
            
            TestResultDto result = systemSettingService.testIntegration(request, userId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("集成测试失败: " + e.getMessage()));
        }
    }
    
    // ========== 系统日志 ==========
    
    @GetMapping("/logs")
    @Operation(summary = "获取系统日志", description = "分页获取系统日志")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResult<SystemLog>>> getSystemLogs(
            @RequestParam(required = false) String level,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate,
            Pageable pageable) {
        try {
            Page<SystemLog> page = systemSettingService.getSystemLogs(level, category, keyword, startDate, endDate, pageable);
            return ResponseEntity.ok(ApiResponse.success(PageResult.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取系统日志失败: " + e.getMessage()));
        }
    }
    
    // ========== 系统通知 ==========
    
    @GetMapping("/notifications")
    @Operation(summary = "获取系统通知", description = "分页获取系统通知")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResult<SystemNotification>>> getSystemNotifications(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Boolean isSent,
            @RequestParam(required = false) String recipient,
            Pageable pageable) {
        try {
            Page<SystemNotification> page = systemSettingService.getSystemNotifications(type, isSent, recipient, pageable);
            return ResponseEntity.ok(ApiResponse.success(PageResult.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取系统通知失败: " + e.getMessage()));
        }
    }
}
